import { z } from "zod";

// 定义表单数据的校验模式
const addressSchema = z.object({
  address: z.string().min(1, { message: "Address is required" }),
  city: z.string().min(1, { message: "City is required" }),
  state: z.string().min(1, { message: "State is required" }),
  // zipCode: z.string().min(1, { message: "Zip Code is required" }),
  zipCode: z.string().optional(), // 去掉必填项
  country: z.string().optional(), // 去掉必填项
  // country: z.string().min(1, { message: "Country is required" }),
});

export type AddressFormData = z.infer<typeof addressSchema>;

export async function submitAddress(
  _: ActionResponse | null,
  formData: FormData
): Promise<ActionResponse> {
  await new Promise((resolve) => setTimeout(resolve, 1000)); // 模拟网络延迟

  try {
    // 修正 rawData 的类型定义，使其与 addressSchema 中的字段名称一致
    const rawData: AddressFormData = {
      address: formData.get("address") as string,
      city: formData.get("city") as string,
      state: formData.get("state") as string,
      zipCode: formData.get("zipCode") as string,
      country: formData.get("country") as string,
    };
    console.log("🚀 ~ rawData:", rawData);

    // 使用 zod 校验模式进行校验
    const validatedData = addressSchema.safeParse(rawData);
    if (!validatedData.success) {
      return {
        success: false,
        message: "please fix the errors in the form",
        errors: validatedData.error.flatten().fieldErrors,
        inputs: rawData,
      };
    }
    return {
      success: true,
      message: "Address submitted successfully",
    };
  } catch (error) {
    return {
      success: false,
      message: "Failed to submit address",
    };
  }
}
